import Router from 'koa-router'
import axios from './utils/axios'

import Passport from './utils/passport'
import md5 from 'crypto-js/md5'

import Cart from '../dbs/models/cart'
import Order from '../dbs/models/order'

let router = new Router({
  prefix: '/order'
})
const sign = '53f12f810b6440b332f75bcb157cbedd'
//------------------------------------------------------------------------------------
router.post('/createOrder', async ctx => {
  let { id, price, count } = ctx.request.body
  console.log(id, price, count)
  let time = Date()
  let orderId = md5(Math.random() * 1000 + time).toString()
  if (!ctx.isAuthenticated())
    return (ctx.body = { code: -1, msg: '你还没有登陆，操作你麻痹' })
  let findCart = await Cart.findOne({ cartNo: id })
  let order = new Order({
    id: orderId,
    count,
    total: price * count,
    time,
    user: ctx.session.passport.user,
    name: findCart.detail[0].name,
    imgs: findCart.detail[0].imgs,
    status: 0
  })
  try {
    let result = await order.save()
    if (!result) return (ctx.body = { code: -1, id: orderId })
    await findCart.remove()
    ctx.body = { code: 0, id: orderId }
  } catch (e) {
    console.log(e)
  }
})
//------------------------------------------------------------------------------------
router.post('/getOrders', async ctx => {
  // console.log("请求order数据")
  if (!ctx.isAuthenticated())
    return (ctx.body = { code: -1, msg: '你还没有登陆，操作你麻痹' })
  try {
    let result = await Order.find() //.limit(15)
    if (result) return (ctx.body = { code: 0, list: result })
    ctx.body = { code: -1, list: [] }
  } catch (e) {
    console.log(e)
  }
})
export default router
